package com.lagou.cl.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;


public class StaticResourceUtil {

	public static String getAbsolutePath(String path) {
		String absolutePath = StaticResourceUtil.class.getResource("/").getPath();
		if ("/".equals(absolutePath.substring(0, 1))) {
			absolutePath = absolutePath.substring(1);
		}
		return absolutePath.replaceAll("\\\\", "/") + path;
	}

	public static void outStaticResouce(InputStream inputStream, OutputStream outputStream) throws IOException {

		int count = 0;
		while (count == 0) {
			count = inputStream.available();
		}

		String resHeader = HttpProtocolUtil.get_200(count);
		outputStream.write(resHeader.getBytes(StandardCharsets.UTF_8));

		//将内容输出

		int resoucesSize = count;

		//已经读取的大小
		int wirtten = 0;

		//每次读取的大小
		int bufferSize = 1024;


		byte[] bytes = new byte[bufferSize];

		while (wirtten < resoucesSize) {
			if ((wirtten + bufferSize) < resoucesSize) {
				bufferSize = resoucesSize - wirtten;
				bytes = new byte[bufferSize];
			}

			inputStream.read(bytes);
			outputStream.write(bytes);

			outputStream.flush();

			//加上每次输出的大小
			wirtten += bufferSize;
		}
	}
}
